import { EmailVerificationCode } from '../models/EmailVerificationCode.js';
import { emailService } from '../utils/emailService.js';
import { User } from '../models/User.js';
import { 
  successResponse, 
  errorResponse, 
  validationErrorResponse,
  conflictResponse 
} from '../utils/response.js';

/**
 * 发送邮箱验证码
 */
export async function sendVerificationCode(req, res) {
  try {
    const { email, type = 'register' } = req.body;

    // 检查邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return validationErrorResponse(res, '請輸入有效的郵箱地址');
    }

    // 如果是注册验证码，检查邮箱是否已被注册
    if (type === 'register') {
      const emailExists = await User.emailExists(email);
      if (emailExists) {
        return conflictResponse(res, '該郵箱已被註冊');
      }
    }

    // 如果是重置密码验证码，检查邮箱是否存在
    if (type === 'reset_password') {
      const emailExists = await User.emailExists(email);
      if (!emailExists) {
        return validationErrorResponse(res, '該郵箱未註冊');
      }
    }

    // 检查是否可以发送新的验证码（防止频繁发送）
    const canSend = await EmailVerificationCode.canSendNewCode(email, type, 1);
    if (!canSend) {
      return errorResponse(res, '發送過於頻繁，請1分鐘後再試', 429);
    }

    // 创建验证码
    const verificationCode = await EmailVerificationCode.create({
      email,
      type,
      expiresInMinutes: 10
    });

    // 发送邮件
    try {
      await emailService.sendVerificationCode(email, verificationCode.code, type);
      
      return successResponse(res, {
        message: '驗證碼已發送',
        expires_at: verificationCode.expires_at
      }, '驗證碼發送成功');
    } catch (emailError) {
      console.error('发送验证码邮件失败:', emailError);

      // 如果邮件发送失败，删除已创建的验证码
      await EmailVerificationCode.markAsUsed(verificationCode.id);

      return errorResponse(res, '驗證碼發送失敗，請檢查郵箱配置或稍後重試', 500);
    }
  } catch (error) {
    console.error('发送验证码失败:', error);
    return errorResponse(res, '驗證碼發送失敗，請稍後重試', 500);
  }
}

/**
 * 验证邮箱验证码
 */
export async function verifyCode(req, res) {
  try {
    const { email, code, type = 'register' } = req.body;

    // 检查邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return validationErrorResponse(res, '請輸入有效的郵箱地址');
    }

    // 检查验证码格式
    if (!code || code.length !== 6 || !/^\d{6}$/.test(code)) {
      return validationErrorResponse(res, '請輸入6位數字驗證碼');
    }

    // 验证验证码
    const isValid = await EmailVerificationCode.verify(email, code, type);

    if (!isValid) {
      return errorResponse(res, '驗證碼無效或已過期', 400);
    }

    return successResponse(res, null, '驗證碼驗證成功');
  } catch (error) {
    console.error('验证验证码失败:', error);
    return errorResponse(res, '驗證碼驗證失敗，請稍後重試', 500);
  }
}

/**
 * 检查验证码状态
 */
export async function checkCodeStatus(req, res) {
  try {
    const { email, type = 'register' } = req.query;

    if (!email) {
      return validationErrorResponse(res, '邮箱地址是必填项');
    }

    // 获取最新的验证码
    const latestCode = await EmailVerificationCode.findLatestByEmailAndType(email, type);
    
    if (!latestCode) {
      return successResponse(res, {
        has_code: false,
        message: '没有找到有效的验证码'
      }, '查询成功');
    }

    const isValid = latestCode.isValid();
    const timeLeft = isValid ? Math.max(0, Math.floor((new Date(latestCode.expires_at) - new Date()) / 1000)) : 0;

    return successResponse(res, {
      has_code: true,
      is_valid: isValid,
      expires_at: latestCode.expires_at,
      time_left: timeLeft,
      created_at: latestCode.created_at
    }, '查询成功');
  } catch (error) {
    console.error('检查验证码状态失败:', error);
    return errorResponse(res, '检查验证码状态失败', 500);
  }
}

/**
 * 清理过期验证码（管理员功能）
 */
export async function cleanupExpiredCodes(req, res) {
  try {
    const cleanedCount = await EmailVerificationCode.cleanupExpired();
    
    return successResponse(res, {
      cleaned_count: cleanedCount
    }, `成功清理${cleanedCount}条过期验证码`);
  } catch (error) {
    console.error('清理过期验证码失败:', error);
    return errorResponse(res, '清理过期验证码失败', 500);
  }
}

/**
 * 获取验证码统计信息（管理员功能）
 */
export async function getVerificationStats(req, res) {
  try {
    const stats = await EmailVerificationCode.getStats();
    
    return successResponse(res, stats, '获取验证码统计成功');
  } catch (error) {
    console.error('获取验证码统计失败:', error);
    return errorResponse(res, '获取验证码统计失败', 500);
  }
}
